<?php
namespace app\index\controller;
use alimsg\Sms;
use app\index\model\User;
use think\Controller;
use think\Loader;
use think\Validate;
use think\captcha\Captcha;

class Reg extends Common
{
    public function index()
    {
        $this->assign('title','注册');
    	return $this->fetch();
    }

    public function send()
    {
        $data = input('post.');

        if(session('exp')&& time()-session('exp')<60){
            $this->error('短信不能发得太频繁');
        }

        $validate = Loader::validate('User');

        if(!$validate->scene('send')->check($data)){
            $this->error($validate->getError());
        }

        $code = mt_rand(167889,999999);

        Sms::send($data['phone'],$code);

        session('code',$code);
        session('phone',$data['phone']);
        session('exp',time());

        $this->success('验证码发送成功');
    }

    public function code()
    {
    	$config =    [
		    // 验证码字体大小
		    'fontSize'    =>    60,    
		    // 验证码位数
		    'length'      =>    2,   
		    // 关闭验证码杂点
		    'useNoise'    =>    false,
		];

    	$captcha = new Captcha($config);
		return $captcha->entry();
    }

    public function check()
    {
    	$data = input('post.');

        $validate = Loader::validate('User');

        if(!$validate->scene('reg')->check($data)){
            $this->error($validate->getError());
        }
        
        $data['password'] = md5($data['password']);
        
        $data['face'] = 'static/index/images/face.jpg';

        $res = User::create($data);
 
    	if($res){
           $this->success("注册成功");  
        }else{
            $this->error('注册失败');
        }
    }
}
